#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2022/1/20 23:23
# @Author  : FLC
# @Contact : beifeng107@foxmail.com
# @File    : department.py
# @Software: PyCharm
from interface.api_object.apis.we_work import WeWork
from interface.api_object.utils.file_tool import FileTool
from interface.api_object.utils.log_tool import logger


class Department(WeWork):

    def __init__(self):
        logger.info("初始化部门管理API对象")
        yaml_data = FileTool.read_yaml("corp_info")
        corp_id = yaml_data.get("corpid").get("mycorp")
        corp_secret = yaml_data.get("corpsecret").get("department")
        self.token = self.get_access_token(corp_id, corp_secret)

    def create(self, data):
        logger.info("创建部门")
        url = "/department/create"
        method = "POST"
        param = {
            "access_token": self.token
        }

        return self.send(method, url, params=param, json=data)

    def search(self):
        logger.info("获取所有部门信息")
        url = "/department/list"
        method = "GET"
        param = {
            "access_token": self.token
        }

        return self.send(method, url, params=param)

    def delete(self, dept_id):
        logger.info(f"删除部门， 部门id是：{dept_id}")
        url = "/department/delete"
        method = "GET"
        param = {
            "access_token": self.token,
            "id": dept_id
        }
        return self.send(method, url, params=param)

    def update(self, data):
        url = "/department/update"
        method = "POST"
        param = {
            "access_token": self.token
        }

        return self.send(method, url, params=param, json=data)

    def is_in_department_list(self, dept_id):
        logger.info("检测部门是否存在")
        r = self.search().json()
        logger.info(f"部门信息为：{r}")
        all_ids = self.json_parser(r, "$..id")
        if all_ids:
            if dept_id in all_ids:
                return True
        return False
